const Service = require('egg').Service

class NewsService extends Service {
  // async list() {
  //   // 查询数据库 或 其他接口 获取数据
  //   return [
  //     { id: 1, title: 'This is news 1', url: '/news/1' },
  //     { id: 2, title: 'This is news 2', url: '/news/2' },
  //     { id: 3, title: 'This is news 3', url: '/news/3' }
  //   ]
  // }
  async list(page = 1) {
    // read config
    const { serverUrl, pageSize } = this.config.news

    // use build-in http client to GET hacker-news api
    const { data: idList } = await this.ctx.curl(`${serverUrl}/topstories.json`, {
      data: {
        orderBy: '"$key"',
        startAt: `"${pageSize * (page - 1)}"`,
        endAt: `"${pageSize * page - 1}"`
      },
      dataType: 'json'
    })

    // parallel GET detail
    const newsList = await Promise.all(
      Object.keys(idList).map((key) => {
        const url = `${serverUrl}/item/${idList[key]}.json`
        return this.ctx.curl(url, { dataType: 'json' })
      })
    )
    return newsList.map((res) => res.data)
  }
}

module.exports = NewsService
